package core;

import fileoperation.FileDeletion;
import gitobject.Commit;
import gitobject.Tree;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.Set;

public class JitMerge {
    public static void merge(String branchName){
        try {
            String nowBranch = JitBranch.getNowBranchName();
            if(Objects.equals(nowBranch, branchName)){
                System.out.println("");
            }
            else{
                if(Objects.equals(branchName, "master")){
                    System.out.println("Can not merge branch 'master'\n\t(use 'jit branch master' and 'jit merge " + nowBranch + "' to merge.");
                }
                else{
                    String mergeCommitId = JitBranch.getCommitId(branchName);
                    String nowCommitId = JitBranch.getCommitId(nowBranch);
                    String LCA = null;
                    Set<String> nowCommitSet = JitMap.getCommitHistorySet(nowCommitId);
                    String commitId = mergeCommitId;
                    while(!Objects.equals(commitId, "" ) && !Objects.equals(commitId, null)){
                        if(nowCommitSet.contains(commitId)) {
                            LCA = commitId;
                            break;
                        }
                        Commit commit = Commit.deserialize(commitId);
                        if(commit == null) {
                            System.out.println("fatal: unknown commit '" + commitId + "'.");
                            return ;
                        }
                        commitId = commit.getParent();
                    }
                    if(Objects.equals(LCA, mergeCommitId)){
                        System.out.println("Already up to date.");
                        FileDeletion.deleteFile(JitBranch.branchPath + File.separator + branchName);
                    }
                    else if(Objects.equals(LCA, nowCommitId)){
                        System.out.println("Updating " + mergeCommitId);
                        System.out.println("Fast-forward");
                        if(JitBranch.writeToBranch(mergeCommitId, nowCommitId))
                            FileDeletion.deleteFile(JitBranch.branchPath + File.separator + branchName);
                    }
                    else{
                        System.out.println("Such merge is not yet supported");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
